﻿using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace YuShiManageSystem.COM{
    /// <summary>Class <c>Validator</c> 提供通用的数据字段验证方法</summary>
    public static class Validator
    {
        /// <summary>根据规则表达式验证</summary>
        /// <param><c>source</c> 这是需要验证的原始数据.</param>
        /// <param><c>regex</c> 验证用的规则表达式.</param>
        /// <returns>验证通过返回：True，否则返回：false.</returns>
        public static bool rule(string source, string regex)
        {
            return Regex.IsMatch(source, regex);
        }

        #region 验证必填值
        /// <summary>验证必填值</summary>
        /// <param><c>source</c> 这是需要验证的原始数据.</param>
        /// <returns>验证通过返回：True，否则返回：false..</returns>
        public static bool Required(string source)
        {
            return !(String.IsNullOrEmpty(source));
        }
        #endregion

        #region 验证长度
        /// <summary>验证长度</summary>
        /// <param><c>source</c> 这是需要验证的原始数据.</param>
        /// <returns>验证通过返回：True，否则返回：false..</returns>
        public static bool length(string source, int minlength, int maxlength)
        {
            int Length = System.Text.Encoding.Default.GetByteCount(source);
            return Length >= minlength && Length <= maxlength;

        }
        #endregion

        #region 验证固定长度
        /// <summary>验证长度</summary>
        /// <param><c>source</c> 这是需要验证的原始数据.</param>
        /// <returns>验证通过返回：True，否则返回：false..</returns>
        public static bool length(string source, int length)
        {
            int Length = System.Text.Encoding.Default.GetByteCount(source);
            return Length == length;

        }
        #endregion

        #region 验证字符是否在4至12之间
        public static bool IsValidByte(string strIn)
        {
            return Regex.IsMatch(strIn, @"^[a-z]{4,12}$");
        }
        #endregion

        #region 验证整数
        /// <summary> 验证整数 </summary>
        /// <param name="source">需要验证的字符串</param>
        /// <returns>TRUE or false</returns>
        /// <remarks></remarks>
        public static bool Num(string source)
        {
            return (Regex.IsMatch(source, @"^(0|[1-9]?[1-9]\d*)$") || String.IsNullOrEmpty(source));
        }
        #endregion

        #region 验证日期型
        /// <summary>验证日期型</summary>
        /// <param><c>source</c> 这是需要验证的原始数据.</param>
        /// <returns>验证通过返回：True，否则返回：false.</returns>
        public static bool Datetime(string source)
        {
            System.DateTime a;
            return System.DateTime.TryParse(source, out a);
        }
        #endregion

        #region 验证Int型
        public static bool IsInt(string source)
        {
            Regex regex = new Regex(@"^(-){0,1}\d+$");
            if (regex.Match(source).Success)
            {
                if ((long.Parse(source) > 0x7fffffffL) || (long.Parse(source) < -2147483648L))
                {
                    return false;
                }
                return true;
            }
            return false;
        }
        #endregion

        #region 验证数字型
        /// <summary>验证数字型</summary>
        /// <param><c>source</c> 这是需要验证的原始数据.</param>
        /// <returns>验证通过返回：True，否则返回：false.</returns>
        public static bool Digit(string source)
        {
            return (Regex.IsMatch(source, @"^([0-9]{1,7})+(\.[0-9]{0,2})?$") || String.IsNullOrEmpty(source));
        }
        #endregion

        #region 验证IP
        public static bool IsIP(string source)
        {
            return Regex.IsMatch(source, @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase);
        }
        public static bool HasIP(string source)
        {
            return Regex.IsMatch(source, @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证IP
        public static bool IsValidIp(string strIn)
        {
            return Regex.IsMatch(strIn, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
        }
        #endregion

        #region 验证手机号
        public static bool IsMobile(string source)
        {
            return Regex.IsMatch(source, @"^1[35]\d{9}$", RegexOptions.IgnoreCase);
        }
        public static bool HasMobile(string source)
        {
            return Regex.IsMatch(source, @"1[35]\d{9}", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证网址
        public static bool IsUrl(string source)
        {
            return Regex.IsMatch(source, @"^(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?$", RegexOptions.IgnoreCase);
        }
        public static bool HasUrl(string source)
        {
            return Regex.IsMatch(source, @"(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证邮箱
        public static bool IsEmail(string source)
        {
            return Regex.IsMatch(source, @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", RegexOptions.IgnoreCase);
        }
        public static bool HasEmail(string source)
        {
            return Regex.IsMatch(source, @"[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证身份证格式
        /// <summary>
        /// 验证身份证号（15位或18位）
        /// </summary>
        /// <param name="cid">身份证号</param>
        /// <returns>是否合法</returns>
        public static bool CheckCid(string cid)
        {
            if (cid.Equals(string.Empty))   //只对格式验证，不对是否为空验证
                return true;
            if (rule(cid, "^\\d+x?$"))
            {
                if (cid.Length == 15)
                {
                    return Idcard15(cid);
                }
                else if (cid.Length == 18)
                {
                    return Idcard18(cid);
                }
               
                else return false;  //长度不对
            }
            else
            {
                return false;
            }
        }
        
        public static bool Idcard18(string source)
        {
            string year = source.Substring(6, 4);
            string month = source.Substring(10, 2);
            string day = source.Substring(12, 2);
            string date = year + "-" + month + "-" + day;
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool Idcard15(string source)
        {
            string year = source.Substring(6, 2);
            string month = source.Substring(8, 2);
            string day = source.Substring(10, 2);
            string date = year + "-" + month + "-" + day;
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 验证身份证是否有效
        public static bool IsIDCard(string Id)
        {
            if (Id.Length == 18)
            {
                bool check = IsIDCard18(Id);
                return check;
            }
            else if (Id.Length == 15)
            {
                bool check = IsIDCard15(Id);
                return check;
            }
            else
            {
                return false;
            }
        }
        public static bool IsIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }
        public static bool IsIDCard15(string Id)
        {
            long n = 0;
            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }
        #endregion

        #region 看字符串的长度是不是在限定数之间 一个中文为两个字符
        public static bool IsLengthStr(string source, int begin, int end)
        {
            int length = Regex.Replace(source, @"[^\x00-\xff]", "OK").Length;
            if ((length <= begin) && (length >= end))
            {
                return false;
            }
            return true;
        }
        #endregion

        #region 是不是中国电话，格式010-85849685
        public static bool IsTel(string source)
        {
            return Regex.IsMatch(source, @"^\d{3,4}-?\d{6,8}$", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证是否为电话号码
        public static bool IsValidTel(string strIn)
        {
            return Regex.IsMatch(strIn, @"(\d+-)?(\d{4}-?\d{7}|\d{3}-?\d{8}|^\d{7,8})(-\d+)?");
        }
        #endregion

        #region 邮政编码 6个数字
        public static bool IsPostCode(string source)
        {
            return Regex.IsMatch(source, @"^\d{6}$", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 中文
        public static bool IsChinese(string source)
        {
            return Regex.IsMatch(source, @"^[\u4e00-\u9fa5]+$", RegexOptions.IgnoreCase);
        }
        public static bool hasChinese(string source)
        {
            return Regex.IsMatch(source, @"[\u4e00-\u9fa5]+", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证是不是正常字符 字母，数字，下划线的组合
        public static bool IsNormalChar(string source)
        {
            return Regex.IsMatch(source, @"[\w\d_]+", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证Email地址
        public static bool IsValidEmail(string strIn)
        {
            // Return true if strIn is in valid e-mail format. 
            return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
        #endregion

        #region dd-mm-yy 的日期形式代替 mm/dd/yy 的日期形式。
        public static string MDYToDMY(String input)
        {
            return Regex.Replace(input, "\\b(?\\d{1,2})/(?\\d{1,2})/(?\\d{2,4})\\b", "${day}-${month}-${year}");
        }
        #endregion

        #region 验证年月日
        public static bool IsValidDate(string strIn)
        {
            return Regex.IsMatch(strIn, @"^2\d{3}-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[1-2]\d|3[0-1])(?:0?[1-9]|1\d|2[0-3]):(?:0?[1-9]|[1-5]\d):(?:0?[1-9]|[1-5]\d)$");
        }
        #endregion

        #region 验证是否为小数
        public static bool IsValidDecimal(string strIn)
        {

            return Regex.IsMatch(strIn, @"[0].\d{1,2}|[1]");
        }
        #endregion

        #region 验证后缀名
        public static bool IsValidPostfix(string strIn)
        {
            return Regex.IsMatch(strIn, @"\.(?i:gif|jpg)$");
        }
        #endregion
    }
}
